package noframe.cases;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Iterator;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * some useful web sites:
 * https://code.google.com/p/selenium/issues/detail?id=284
 * https://groups.google.com/forum/?fromgroups=#!topic/webdriver/Wi1-1U9snTs
 * http://blog.csdn.net/vagabond1/article/details/7730913
 */

public class ModleDialogExample {
	public static void main(String[] args) {

		// WebDriver driver= new ChromeDriver();
		WebDriver driver = new FirefoxDriver();
		driver.get("https://developer.mozilla.org/samples/domref/showModalDialog.html");

		(new WebDriverWait(driver, 20)).until(new ExpectedCondition<Boolean>() {
			public Boolean apply(WebDriver d) {
				return d.findElement(By.xpath("/html/body/input")).isDisplayed();
			}
		});

		WebElement button = driver.findElement(By.xpath("/html/body/input"));
		button.sendKeys("");
		try {
			Robot robot = new Robot();
//			robot.mouseMove(65, 125);
//			robot.mousePress(InputEvent.BUTTON1_MASK);
//		    robot.mouseRelease(InputEvent.BUTTON1_MASK);
			robot.keyPress(KeyEvent.VK_ENTER);
			robot.keyRelease(KeyEvent.VK_ENTER);
			Thread.sleep(500);
		} 
		catch (AWTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		 catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		
		Set<String> handles = driver.getWindowHandles();
		System.out.println(handles.size());
		Iterator<String> ite = handles.iterator();
		ite.next();
		String current =ite.next();
		driver.switchTo().window(current);

		(new WebDriverWait(driver, 20)).until(new ExpectedCondition<Boolean>() {
			public Boolean apply(WebDriver d) {
				return d.findElement(By.xpath("//*[@type='button']")).isDisplayed();
			}
		});
		
		WebElement close = driver.findElement(By.xpath("//*[@type='button']"));
		System.out.println(driver.getCurrentUrl());
		close.click();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		driver.quit();
	}
}
